import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Picker, ImageUploader, TextArea, Collapse } from 'antd-mobile';
import { AddOutline, DownOutline, UpOutline } from 'antd-mobile-icons';
import styles from './index.module.less';
import HeaderNav from "@/components/header-nav"
import { useSearchParams } from 'react-router-dom';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { postCreateRole, postEditRole } = $globalServicer('chat')
import TagSelector from '@/components/TagSelector';
import { handleImageUpload } from '@/utils/upload';
import { genderColumns, raceColumns, world_categoryColumns, era_backgroundColumns, ROLE_DESCRIPTION_FIELDS } from '@/utils/constant';
const AddRoleForm = () => {
  const [form] = Form.useForm();
  const [params] = useSearchParams();
  const customNavigate = $globalNavigate()
  const role_id = params.get('role_id');
  const [submitting, setSubmitting] = useState(false);
  const [activeKey, setActiveKey] = useState('');
  const isRequired = true;
  const onFinish = (values) => {
    console.log('Form values:', values);
    if (submitting) return; // 如果正在提交，直接返回
    let resultData = {
      cover: values.cover[0].url,
      persona_name: values.persona_name,
      description: {
        gender: values.gender,
        age: values.age,
        race: values.race,
        appearance: values.appearance,
        background: values.background,
        experience: values.experience,
        relationships: values.relationships,
        abilities: values.abilities,
        custom_content: values.custom_content,
      },
      remarks: values.remarks,
    }
    try {
      setSubmitting(true);
      postCreateRole(resultData).then(res => {
        console.log("🚀 ~ onFinish ~ res:", res)
        customNavigate(`/personasList?role_id=${role_id}`)
        showSuccessToast('创建成功')
      })
    } catch (error) {
      showErrorToast('提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };
  const handleAddOption = (option) => {
    console.log(`======option`, option)
  }
  return (
    <div className={styles.formContainer}>
      <div className="header">
        <HeaderNav backArrow={true}
          onBack={() => {
            customNavigate(`/personasList?role_id=${role_id}`)
          }}
          title={'创建聊天角色'}
        ></HeaderNav>
      </div>
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div className={styles.footer}>
            <Button className={styles.submitButton}
              type='submit'
              loading={submitting}
              disabled={submitting}
            >{submitting ? '提交中...' : '完成'}</Button>
          </div>
        }
      >
        <Form.Item name="cover" label="头像" className={styles.imageItem} required={isRequired} rules={[{ required: isRequired, message: '头像不能为空' }]}>
          <ImageUploader className={styles.uploadWrapper}
            upload={handleImageUpload}
            maxCount={1}
            onDelete={() => {
              return { beforeDelete: () => true };
            }} />
        </Form.Item>
        <Form.Item name="persona_name" label="名称" required={isRequired} rules={[{ required: isRequired, message: '名称不能为空' }]}>
          <Input placeholder="请输入名称" />
        </Form.Item>
        <TagSelector
          name="gender"
          label="性别"
          options={genderColumns}
          multiple={false}
          maxCount={20}
          help='字数上限10'
          required={isRequired}
          rules={[{ required: isRequired, message: '性别不能为空' }]}
          onAddOption={handleAddOption}
        />
        <Form.Item name="age" label="年龄" help='字数上限10' required={isRequired} rules={[{ required: isRequired, message: '年龄不能为空' }]}>
          <Input placeholder="请输入年龄" maxLength={20} />
        </Form.Item>
        <TagSelector
          name="race"
          label="种族"
          options={raceColumns}
          multiple={false}
          required={isRequired}
          rules={[{ required: isRequired, message: '种族不能为空' }]}
          maxCount={40}
          help='字数上限20'
          onAddOption={handleAddOption}
        />
        {/* <Form.Item name="race" label="种族" help=''>
          <Input placeholder="请选择种族" onClick={() => {
            setVisible(true)
          }} />
        </Form.Item> */}
        <Collapse
          activeKey={activeKey}
          onChange={(activeKey) => {
            setActiveKey(activeKey)
          }}
        >
          <Collapse.Panel key='1'
            title={activeKey?.indexOf('1') ? '展开' : '收起'}
            className={styles.collapsePanelWrapper}>
            <Form.Item name="appearance" label="外貌衣着" help='字数上限100'>
              <Input placeholder="输入外貌衣着（字数上限100）" maxLength={200} />
            </Form.Item>
            <Form.Item name="background" label="人物背景" help='字数上限10'>
              <Input placeholder="输入人物背景（字数上限100）" maxLength={200} />
            </Form.Item>
            <Form.Item name="experience" label="人物经历" help='字数上限100'>
              <Input placeholder="输入人物经历（字数上限100）" maxLength={200} />
            </Form.Item>
            <Form.Item name="relationships" label="人际关系" help='字数上限100'>
              <Input placeholder="输入人际关系（字数上限100）" maxLength={200} />
            </Form.Item>
            <Form.Item name="abilities" label="能力设定" help='字数上限100'>
              <Input placeholder="输入能力设定（字数上限100）" maxLength={200} />
            </Form.Item>
            <Form.Item name="custom_content" label="自定义内容" help='字数上限200'>
              <Input placeholder="输入自定义内容（字数上限100）" maxLength={400} />
            </Form.Item>
            <Form.Item name="remarks" label="备注" help="字数上限20">
              <Input placeholder="" maxLength={40} />
            </Form.Item>
          </Collapse.Panel>
        </Collapse>
      </Form>
    </div>
  );
};

export default AddRoleForm;